package org.jmeter.tcp.helmet.gps;

import com.alibaba.fastjson.JSON;
import org.apache.jorphan.logging.LoggingManager;
import org.apache.log.Logger;

import java.util.ArrayList;
import java.util.Date;
import java.util.List;
import java.util.concurrent.ConcurrentHashMap;
import java.util.concurrent.ScheduledExecutorService;
import java.util.concurrent.TimeUnit;

public class GpsPushTask implements Runnable{
    protected static final Logger log = LoggingManager.getLoggerForClass();

    /**
     * 正在运行中的任务
     * key：imei号
     */
    public static ConcurrentHashMap<String, GpsPushTask> runningTask = new ConcurrentHashMap<>();

    ScheduledExecutorService executorService;

    // 推送速度
    int speed = 1;
    // 每次推送的条数
    int batchSize = 10;

    List<Gps> gpsList;
    String imei;

    int start = 0;
    List<Gps> willPushGps; // 要推送的gps数据

    long diff; // = 开始推送时间 - 第一条gps时间的差值
    long preTime; // 上一条gps的推送时间
    long firstTime; // 第一条gps的时间

    public GpsPushTask (ScheduledExecutorService executorService, String imei, List<Gps> gpsList){
        this.executorService = executorService;
        this.imei = imei;
        this.gpsList = gpsList;
        willPushGps = new ArrayList<>(batchSize);
        //
        long now = System.currentTimeMillis();
        preTime = now;
        diff = now - gpsList.get(0).getLocationTime().getTime();
        firstTime = gpsList.get(0).getLocationTime().getTime();
    }

    @Override
    public void run() {
        // 执行推送
        if(willPushGps != null && willPushGps.size() > 0){
            try {
                pushGps(willPushGps);
            } catch (Exception e) {
                e.printStackTrace();
            }
            // 清空
            willPushGps.clear();
        }

        // 所有数据推送完成，结束
        if(start >= gpsList.size()){
            runningTask.remove(this.imei); // 移除任务
            return;
        }

        // 计算下次推送的gps，及其下次推送的时间，并投递任务
        long totalWaitTime = 0;
        for(int i = start; i < start + batchSize && i < gpsList.size(); i++){
            Gps gps = gpsList.get(i);

            Date time = new Date((gps.getLocationTime().getTime() - firstTime)/speed + firstTime + diff);
            gps.setLocationTime(time);
            gps.setImei(imei);

            totalWaitTime += time.getTime() - preTime;
            preTime = time.getTime();

            willPushGps.add(gps);
        }
        //
        start += batchSize;

        // 投递任务，下次执行时机
        if(totalWaitTime < 0){
            log.info("设置下次推送时间异常" + totalWaitTime);
            totalWaitTime = 0;
        }
        executorService.schedule(this, totalWaitTime, TimeUnit.MILLISECONDS);

    }

    public void pushGps(List<Gps> willPushGps){
        String str = JSON.toJSONString(willPushGps);
        log.info("当前推送开始"+(start - batchSize)+"，共"+willPushGps.size()+"条："+str);
    }


}